package com.banyuan.servlet;

import org.apache.commons.io.FileUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/ajax2")
public class Ajax2Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        StringBuffer sb = new StringBuffer();
        String jianStr = req.getParameter("jian");
        for (int i = 0; i < jianStr.length(); i++) {
            char c = jianStr.charAt(i);
            String jian = String.valueOf(c);
            Map<String, String> map = getMap();
            String fan = map.get(jian);

            if (fan != null) {
                sb.append(fan);
            } else {
                sb.append(jian);
            }
        }
        resp.getWriter().write(sb.toString());

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    public Map<String,String> getMap() throws IOException {
        Map<String,String> map = new HashMap<>();
        List<String> stringList = FileUtils.readLines(new File("/Users/edy/Desktop/jf_map_utf8.txt"), "UTF-8");
        for (String s : stringList) {
            String[] split = s.split(":");
            map.put(split[0],split[1]);
        }
        return map;
    }
}
